﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
using Wizard.UI;

namespace AppScan
{
    public partial class TargetsPage : InternalWizardPage
    {
        private readonly CreateUserContext _context;
        private string[] default_txt = { "IPv4 address only", " (i.e 192.168.1.55)", "(i.e 192.168.1.230)", "\\DOMAIN (or \\sub.domain.top)", "Select a file to open  ->" };
        public TargetsPage(CreateUserContext context)
        {
            _context = context;
            InitializeComponent();
        }

        private void UserNamePage_SetActive(object sender, CancelEventArgs e)
        {
            EnableControls();
       }

        private void EnableControls()
        {
            bool nextEnabled = true;

            //if (string.IsNullOrEmpty(singleTargetIP_box.Text) || singleTargetIP_box.Text.Contains("\\hostname or IPv4 address"))
            //    nextEnabled = false;
            //if (string.IsNullOrEmpty(IPrange1_box.Text) || IPrange1_box.Text.Contains("(i.e"));
            //    nextEnabled = false;
            //if (string.IsNullOrEmpty(IPrange2_box.Text) || IPrange2_box.Text.Contains("(i.e"));
            //    nextEnabled = false;
            //if (string.IsNullOrEmpty(filename_box.Text) || filename_box.Text.Contains("Select "));
            //    nextEnabled = false;
            if (dataGridView1.RowCount < 2)
                nextEnabled = false;

            if (nextEnabled)
                SetWizardButtons(WizardButtons.Back | WizardButtons.Next);
            else
                SetWizardButtons(WizardButtons.Back);
        }

        private void userNameTextBox_TextChanged(object sender, EventArgs e)
        {
            EnableControls();
        }

        private void fullNameTextBox_TextChanged(object sender, EventArgs e)
        {
            EnableControls();
        }

        private void UserNamePage_WizardNext(object sender, WizardPageEventArgs e)
        {
            //needs to change
            //_context.targeta = singleTargetIP_box.Text;
            //_context.FullName = IPrange1_box.Text;
            //_context.Description = domainName_box.Text;

            //First, check to see if box is empty
            if (dataGridView1.RowCount < 1)
            {
                MessageBox.Show("No targets import\nPlease import targets to scan.");
            }

            //next ensure all items in the datagridview are accounted for.
            //maybe we use another list here?

            /**********
             * 
             *  foreach row in dgv
             *      obj.var = row[0]
             * 
             *      List.Add(obj);
             * **********/
            string collect = string.Empty;
            for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
            {
                try
                {
                    if (String.IsNullOrEmpty(dataGridView1.Rows[i].Cells[0].Value.ToString()))
                    {
                        collect += "INVALID TARGET;";
                    }
                    else
                    {
                        collect += dataGridView1.Rows[i].Cells[0].Value.ToString()+";";
                    }
                }
                catch
                {
                    //value must be null, ignore
                }
            }
            _context.targeta = collect.Split(new string[] {";"},StringSplitOptions.RemoveEmptyEntries);
        }

        private void Banner_Load(object sender, EventArgs e)
        {

        }

        private void fix_spacing()
        {
            




        }

        private void IPrange1_box_TextChanged(object sender, EventArgs e)
        {

        }

        private void add_btn_Click(object sender, EventArgs e)
        {
            //cycle through enabled controls and add the enabled ones.
            cyclic();
            EnableControls();
        }

        private void cyclic()
        {
            bool cont = true;
            //if ip range is checked, sanitize input
            foreach (object txt in this.splitContainer1.Panel1.Controls)
            {
                if (txt.GetType() == typeof(TextBox))
                {
                    if ((txt as TextBox).Name.Contains("filename"))
                    {
                        if ((txt as TextBox).Text.ToLower().Contains("select a file"))
                        {
                            //default
                        }
                        else
                        {
                            //parse it :-)
                            /**************
                             * Text file should look like:
                             * 
                             * 10.0.2.1
                             * 10.3.1.1
                             * 11.9.1.2
                             * 12.23.33.21
                             * 
                             * *************/

                            string[] hosts = readit((txt as TextBox).Text);
                            foreach (string str in hosts)
                            {
                                if (str.Length == 0 || str == "$ERROR")
                                {
                                    //do nothing
                                }
                                else
                                {
                                    bool check = sanity(txt);
                                    if (check)
                                        add_dgv(str);
                                    else
                                    {
                                        MessageBox.Show("Host " + str + " is not a valid IPv4 address. \n At this time, only IPv4 addresses are supported.");
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        if (txt.GetType() == typeof(TextBox))
                        {
                            if ((txt as TextBox).Enabled == true)
                            {
                                if ((txt as TextBox).Name.Contains("range"))
                                {
                                    if ((txt as TextBox).Name.Contains("range1"))
                                    {
                                        cont = sanity(IPrange1_box, IPrange2_box);
                                        //funky IPv4 maths
                                        if (cont)
                                        {
                                            string[] ranged = funkyIPv4Maths();

                                            foreach (string str in ranged)
                                            {
                                                if (string.IsNullOrEmpty(str))
                                                {
                                                }
                                                else
                                                {
                                                    add_dgv(str);
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    if ((txt as TextBox).Name.ToLower().Contains("single"))
                                    {
                                        bool check = sanity(txt);
                                        if (check)
                                        {
                                            //add to datagridview
                                            add_dgv((txt as TextBox).Text);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        private string[] funkyIPv4Maths()
        {
            string [] ipv4 = {string.Empty};
            string first = IPrange1_box.Text;
            string last = IPrange2_box.Text;

            string[] class1 = first.Split('.');
            string[] class2 = last.Split('.');
            string collector = string.Empty;

            if (Int32.Parse(class1[0]) != Int32.Parse(class2[0]) || Int32.Parse(class1[0]) != Int32.Parse(class2[0]) || Int32.Parse(class1[1]) != Int32.Parse(class2[1]) || Int32.Parse(class1[2]) != Int32.Parse(class2[2]))
            {
                MessageBox.Show("Class C (0/24) ranges supported only at this time\n.Please ensure both networks are in the same Class C subnet.");
            }
            else
            {
                //if (Int32.Parse(class1[0]) <= Int32.Parse(class2[0]))
                //{
                //    //...

                //    for (int z = Int32.Parse(class1[2]); z <= Int32.Parse(class2[2]); z++)
                //    {
                if (Int32.Parse(class1[3]) <= Int32.Parse(class2[3]))
                {
                    //...Same class.  this is easy
                    for (int i = Int32.Parse(class1[3]); i < Int32.Parse(class2[3]) + 1; i++)
                    {
                        collector += class1[0] + "." + class1[1] + "." + class1[2] + "." + i + ";";
                    }
                }
                //    }
                //}
            }
            ipv4 = collector.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);

            return ipv4;
        }

        private string[] readit(string filename)
        {
            try
            {
                using (System.IO.StreamReader sR = new System.IO.StreamReader(filename))
                {
                    string line = string.Empty;
                    string collector = string.Empty;
                    while ((line = sR.ReadLine()) != null)
                    {
                        line = line +";";
                        collector = collector + line;
                    }
                    sR.Close();
                    sR.Dispose();
                    string[] hosts = collector.Split(';');
                    return hosts;
                }
                
            }
            catch
            {
                string[] err = new string[1] { "$ERROR" };
                return err ;
            }
        }

        private bool sanity(object txt)
        {
            try
            {
                System.Net.IPAddress ip = System.Net.IPAddress.Parse((txt as TextBox).Text.ToString());
                return true;
            }
            catch
            {
                MessageBox.Show("IP Range is invalid, please double check input");
                return false;
            }

        }

        private bool sanity(object txt, object txt2)
        {
            try
            {
                System.Net.IPAddress ip = System.Net.IPAddress.Parse((txt as TextBox).Text.ToString());
                System.Net.IPAddress ip2 = System.Net.IPAddress.Parse((txt2 as TextBox).Text.ToString());
                return true;
            }
            catch
            {
                MessageBox.Show("IP Range is invalid, please double check input");
                return false;
            }

        }

        private void add_dgv(string item)
        {
            dataGridView1.Rows.Add(item);
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if ((sender as RadioButton).Checked == true)
                radio_enabler((sender as RadioButton).Name);
        }

        private void radio_enabler(string radiobtn_name)
        {
            foreach (object radio in this.splitContainer1.Panel1.Controls)
            {
                
                if (radio.GetType()== typeof(RadioButton))
                {
                    if ((radio as RadioButton).Name == radiobtn_name && (radio as RadioButton).Checked == true)
                    {
                        //(radio as RadioButton).Checked = true;
                        string[] split = radiobtn_name.Split('_');
                        txt_enabler(split[0]);
                        //enable text_boxes with similar names
                    }
                    else
                    {
                        (radio as RadioButton).Checked = false;

                    }
                }
            }

        }

        private void txt_enabler(string Name)
        {
            foreach (object txt in this.splitContainer1.Panel1.Controls)
            {
                if (txt.GetType() == typeof(TextBox))
                {
                    if ((txt as TextBox).Name.ToLower().Contains(Name.ToLower()))
                    {
                        (txt as TextBox).Enabled = true;
                        (txt as TextBox).Text = "";
                        (txt as TextBox).ForeColor = System.Drawing.Color.Black;
                        (txt as TextBox).Font = new System.Drawing.Font((txt as TextBox).Font.Name, (txt as TextBox).Font.Size, System.Drawing.FontStyle.Regular, (txt as TextBox).Font.Unit);
                    }
                    else
                    {
                        //(txt as TextBox).BackColor = System.Drawing.Color.Gray;
                        (txt as TextBox).Enabled = false;
                        
                        //(txt as TextBox).Text = "";
                    }
                }

            }

        }

        private void open_file_btn_Click(object sender, EventArgs e)
        {
            //Stream myStream = null;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            string path = Directory.GetCurrentDirectory(); 
            openFileDialog1.InitialDirectory = path;
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    //if ((myStream = openFileDialog1.OpenFile()) != null)
                    //{
                    //    using (myStream)
                    //    {
                    //        // Insert code to read the stream here.
                    //    }
                    //}
                    filename_box.Text = openFileDialog1.FileName;

                }
                catch (Exception ex)
                {
                   // MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

        private void singleTargetIP_box_Click(object sender, EventArgs e)
        {
            foreach (string str in default_txt)
            {
                if ((sender as TextBox).Text.ToString().ToLower().Contains(str.ToLower()))
                {
                    (sender as TextBox).ForeColor = System.Drawing.Color.Black;
                    (sender as TextBox).Font = new System.Drawing.Font((sender as TextBox).Font.Name, (sender as TextBox).Font.Size, System.Drawing.FontStyle.Regular, (sender as TextBox).Font.Unit); 
                
                    (sender as TextBox).Text = "";
                 }
            }
        }

        private void remove_btn_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                System.Diagnostics.Debug.WriteLine(dataGridView1.Rows[i].Cells[0].Value);
                if (dataGridView1.Rows[i].Cells[0].Selected)
                {
                    dataGridView1.Rows.Remove(dataGridView1.Rows[i]);
                }
            }
            EnableControls();
        }

        private void ClearALL_btn_Click(object sender, EventArgs e)
        {
            DialogResult result;
            result = MessageBox.Show("Are you sure you want to clear targets list?", "Clear Targets?", MessageBoxButtons.YesNo);
            if (result == DialogResult.No)
            {
                MessageBox.Show("Targets NOT cleared.");
            }
            if (result == DialogResult.Yes)
            {
                dataGridView1.Rows.Clear();
                //for (int i = dataGridView1.Rows.Count - 2; i >= 0; i--)
                //{
                //    System.Diagnostics.Debug.WriteLine(dataGridView1.Rows[i].Cells[0].Value);

                //    if (string.IsNullOrEmpty(dataGridView1.Rows[i].Cells[0].Value.ToString()))
                //    {

                //    }
                //    else
                //    {
                        
                //        dataGridView1.Rows.Remove(dataGridView1.Rows[i]);
                //    }
                //}
            }
        }
    }
}
